package com.borrowing.controller;

import com.borrowing.entity.Result;
import com.borrowing.entity.pojo.User;
import com.borrowing.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


/**
 * 文件
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private UserMapper userMapper;
    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/upload2")
    public Result uploadFile(MultipartFile file,Integer userId) {

        User user = userMapper.selectById(userId);
        if(user == null){
            return Result.fail("输入的id不存在");
        }
        try {
            // 确保目录存在
            File uploadDir = new File("D:/no-use/interviewPicture");
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 保存文件
            String fileUrl = "D:/no-use/interviewPicture"+"/"+user.getUserName()+"-"+file.getOriginalFilename();
            File targetFile = new File(uploadDir, user.getUserName()+"-"+file.getOriginalFilename());
            file.transferTo(targetFile);

            user.setPicture(fileUrl);
            userMapper.updateById(user);
            return Result.ok("文件上传成功: ");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("文件上传失败: ");
        }
    }

}
